<template>
    <div class="drawing-board-container">
      <div class="toolbar">
        <input type="color" v-model="currentColor">
        <select v-model="currentWidth">
          <option v-for="w in [2,4,6,8,10]" :value="w" :key="w">{{ w }}px</option>
        </select>
        <button @click="clearCanvas">清空</button>
      </div>
      <canvas 
        ref="canvas"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
      ></canvas>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  
  const canvas = ref(null)
  let ctx = null
  let isDrawing = false
  let lastX = 0
  let lastY = 0
  
  const currentColor = ref('#000000')
  const currentWidth = ref(4)
  
  onMounted(() => {
    initCanvas()
  })
  
  function initCanvas() {
    ctx = canvas.value.getContext('2d')
    resizeCanvas()
    
    // 高分屏适配
    const dpr = window.devicePixelRatio || 1
    ctx.scale(dpr, dpr)
  }
  
  function resizeCanvas() {
    const container = canvas.value.parentElement
    canvas.value.width = container.clientWidth * devicePixelRatio
    canvas.value.height = container.clientHeight * devicePixelRatio
    canvas.value.style.width = '100%'
    canvas.value.style.height = '100%'
  }
  
  function startDrawing(e) {
    isDrawing = true
    const rect = canvas.value.getBoundingClientRect()
    const scale = canvas.value.width / rect.width
    lastX = (e.clientX - rect.left) * scale
    lastY = (e.clientY - rect.top) * scale
  }
  
  function draw(e) {
    if (!isDrawing) return
    const rect = canvas.value.getBoundingClientRect()
    const scale = canvas.value.width / rect.width
    const x = (e.clientX - rect.left) * scale
    const y = (e.clientY - rect.top) * scale
  
    ctx.beginPath()
    ctx.moveTo(lastX, lastY)
    ctx.lineTo(x, y)
    ctx.strokeStyle = currentColor.value
    ctx.lineWidth = currentWidth.value
    ctx.lineCap = 'round'
    ctx.stroke()
  
    lastX = x
    lastY = y
  }
  
  function stopDrawing() {
    isDrawing = false
  }
  
  function clearCanvas() {
    ctx.clearRect(0, 0, canvas.value.width, canvas.value.height)
  }
  </script>
  
  <style scoped>
  .drawing-board-container {
    width: 100%;
    height: calc(100vh - 100px);
    position: relative;
  }
  
  .toolbar {
    position: absolute;
    top: 10px;
    left: 10px;
    background: white;
    padding: 10px;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    z-index: 10;
  }
  
  canvas {
    border: 1px solid #ddd;
    background: white;
    touch-action: none; /* 禁止触摸滚动 */
  }
  </style>
  